from SiderTools import *
import requests

music_types = [
    {
        'name': "华语",
        'subCateId': "2368"
    },
    {
        'name': "欧美",
        'subCateId': "2369"
    }
]

# 1、加密sign,发送请求，获取数据
def get_json(page, publicObj):
    timestamp = publicObj.getTimeStamp()
    args = {
        "sign": "",
        "appid": publicObj.appid,  # 固定
        "subCateId": music_types[1]['subCateId'],  # 类别，获取欧美类别的歌曲
        "pageNo": page,  # 第几页
        "timestamp": timestamp,  # 时间
        'pageSize': 50  # 每页的数据
    }
    signParam = "appid={0}&pageNo={1}&pageSize={2}&subCateId={3}&timestamp={4}{5}".format(
        args['appid'], args['pageNo'], args['pageSize'], args['subCateId'], timestamp, publicObj.secret)
    print("加密之前signParm", signParam)
    # 加密
    args['sign'] = publicObj.mdEncode(signParam)
    print(f"最终的参数{args}")

    result = requests.get(url=publicObj.song_sheet_type, params=args)
    json = result.json()
    print(f"获取到的数据{json}")

    # 解析数据并写入 CSV
    if json.get('data', {}).get('result'):
        data_to_save = []
        for item in json['data']['result']:
            row = [
                item.get('id', ''),
                item.get('pic', ''),
                item.get('title', ''),
                item.get('desc', ''),
                ",".join(item.get('tagList', [])),  # 将列表转为字符串
                item.get('resourceType', ''),
                item.get('trackCount', ''),
                item.get('addDate', '')
            ]
            data_to_save.append(row)

        # 调用工具类方法写入 CSV
        publicObj.init_song_sheet_data(data_to_save)
        print(f"第 {page} 页数据已保存到 CSV")
    else:
        print("未获取到有效数据")


# 4、存储数据
if __name__ == '__main__':
    publicObj = PublicSiderTools()
    publicObj.create_song_sheet_type()
    get_json(1, publicObj)